//
//  FSNewEmailViewController.m
//  Trade
//
//  Created by 刘沿 on 16/4/15.
//  Copyright © 2016年 刘沿. All rights reserved.
//

#import "FSNewEmailViewController.h"
#import "GDataDefines.h"


@interface FSNewEmailViewController ()

@end

@implementation FSNewEmailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getSelectName:) name:@"PostSelectNameNoti" object:nil];
    [self setupTextFieldRightView];
    
    [self setValueToView];

}

-(void)viewWillAppear:(BOOL)animated{

[super viewWillAppear:animated];

[IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;

[IQKeyboardManager sharedManager].enable = NO;

}

//

-(void)viewWillDisappear:(BOOL)animated{



[IQKeyboardManager sharedManager].enable = YES;

}

-(void)getSelectName:(NSNotification*)note{
    
    NSArray * array = note.userInfo[@"SelectName"];
    
    self.sendTextField.text = [array componentsJoinedByString:@","];
    
}

#pragma mark 设置右边的view
-(void)setupTextFieldRightView{
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(keybordDown)];
    [self.view addGestureRecognizer:tap];
    
    UIView * rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    rightView.backgroundColor = [UIColor clearColor];
    UIButton * addNameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addNameBtn setImage:[UIImage imageNamed:@"addName.png"] forState:UIControlStateNormal];
    addNameBtn.frame = CGRectMake(0, 0, 30, 30);
    [addNameBtn addTarget:self action:@selector(addNameAction:) forControlEvents:UIControlEventTouchUpInside];
    [rightView addSubview:addNameBtn];
    
    self.sendTextField.rightView = rightView;
    self.sendTextField.rightViewMode=UITextFieldViewModeAlways;
}

-(void)setValueToView{
    if (self.type == Reply) {//回复
        self.title = @"回复";
        self.sendTextField.rightView = [[UIView alloc] init];
        self.sendTextField.text = self.detailModel.sender;
        self.subjectTextField.text = self.detailModel.subject;
        
    }else if (self.type == Retweet) //转发
    {
        self.subjectTextField.text = self.detailModel.subject;
        self.title = @"转发";
    }else{
        self.title = @"发邮件";
    }
}


#pragma mark 添加发送人
-(void)addNameAction:(UIButton*)btn{
    
    UIStoryboard * stroyBoard = [UIStoryboard storyboardWithName:@"MaoCuHui" bundle:nil];
    FSMainAdressViewController * mainAddressVC = [stroyBoard instantiateViewControllerWithIdentifier:@"mainAddressVCID"];
    [self.navigationController pushViewController:mainAddressVC animated:YES];
    
    //    OACityNameViewController * nameVC = [[OACityNameViewController alloc]init];
    //    __weak typeof(self) weakSelf = self;
    //    nameVC.GetNameStringBlock = ^(NSString * str){
    //        weakSelf.sendTextField.text = str;
    //    };
    
    
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (textField == self.sendTextField) {
        return NO;
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (void)keybordDown {
    [self.contentText resignFirstResponder];
    [self.sendTextField resignFirstResponder];
    [self.subjectTextField resignFirstResponder];
}

- (IBAction)sendEmail:(id)sender {
    [self keybordDown];
    
    if ([self.sendTextField.text length] == 0) {
        [self.view makeToast:@"对不起，你的收件人不可以为空"];
        return;
    }
    if ([self.subjectTextField.text length] == 0) {
        [self.view makeToast:@"对不起，你的主题不可以为空"];
        return;
    }
    
    if ([self.contentText.text length] ==0) {
        [self.view makeToast:@"对不起，你的内容不可以为空"];
        return;
    }
    
    [self uploadEmail];

    
}

-(NSString *)returnString
{
    NSString *string = [[NSString alloc]init];
    string = @"&lt;名称&gt;%@&lt;/名称&gt;\n"
    "&lt;内容&gt;%@&lt;/内容&gt;\n";
    
    NSMutableString *str = [NSMutableString string];
    for (int i = 0; i<self.attachmentArray.count; i++) {
        FSAttachmentModel * attachModel = self.attachmentArray[i];
        [str appendString: [NSString stringWithFormat:string,attachModel.attachmentsTitle,attachModel.attachmentsURL]];
    }
    
    return str;
}


-(void)uploadEmail{
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSString * password = [[NSUserDefaults standardUserDefaults]objectForKey:@"pwdId"];
    NSString * body = nil;
    if (self.type == Retweet) {
        
        body =  [NSString stringWithFormat:@"&lt;?xml version=\'1.0\' encoding=\'utf-8\'?&gt;\n"
                 "&lt;交换 xmlns=\'exch.jhsx.gov.cn/data\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\'&gt;\n"
                 "&lt;数据&gt;\n"
                 "&lt;数据要素&gt;\n"
                 "&lt;Subject&gt; %@ &lt;/Subject&gt;\n"
                 "&lt;SendTo&gt; %@ &lt;/SendTo&gt;\n"
                 "&lt;body&gt; %@ &lt;/body&gt;\n"
                 "&lt;/数据要素&gt;\n"
                 "&lt;附件&gt;\n"
                 "%@"
                 "&lt;/附件&gt;\n"
                 "&lt;/数据&gt;\n"
                 "&lt;/交换&gt;"
                 ,self.subjectTextField.text,self.sendTextField.text,self.contentText.text,[self returnString]];
    }else{
        body =  [NSString stringWithFormat:@"&lt;?xml version=\'1.0\' encoding=\'utf-8\'?&gt;\n"
                 "&lt;交换 xmlns=\'exch.jhsx.gov.cn/data\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\'&gt;\n"
                 "&lt;数据&gt;\n"
                 "&lt;数据要素&gt;\n"
                 "&lt;Subject&gt; %@ &lt;/Subject&gt;\n"
                 "&lt;SendTo&gt; %@ &lt;/SendTo&gt;\n"
                 "&lt;body&gt; %@ &lt;/body&gt;\n"
                 "&lt;/数据要素&gt;\n"
                 "&lt;/数据&gt;\n"
                 "&lt;/交换&gt;"
                 ,self.subjectTextField.text,self.sendTextField.text,self.contentText.text ];
    }
    
    
    NSArray * array = @[@{@"userId":userId},@{@"pwdId":password},@{@"famxml":body}];
    [HttpTools postWithURL:KexchmailURL arrays:array method:KSendMailMethod success:^(id JSON) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: [JSON dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
        GDataXMLElement *rootElement = [doc rootElement];
        NSArray *arrData= [rootElement elementsForName:@"info"];
        NSString * message= nil;
        for (GDataXMLElement * subXMLElement in arrData) {
            GDataXMLElement * element = [[subXMLElement elementsForName:@"msg"] objectAtIndex:0];
            message  = [element stringValue];
        }
        if ([message isEqualToString:@"1044"]) {
            [self.view makeToast:@"发送失败"];
        }else{
            [self.view makeToast:@"发送成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshData" object:nil]; //刷新发件箱，收件箱 数据
            [self.navigationController popViewControllerAnimated:YES];
            
        }
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        [self.view makeToast:@"发送失败"];
    }];
    
}
-(void)textViewDidBeginEditing:(UITextView *)textView{

//这里的offset的大小是控制着呼出键盘的时候view上移多少。比如上移20，就给offset赋值-20，以此类推。也可以根据屏幕高度的不同做一个if判断。

float offset = 0.0f;

if(_contentText == textView){

offset = -20;

}

NSTimeInterval animationDuration = 0.30f;

[UIView beginAnimations:@"ResizeForKeyBoard"context:nil];

[UIView setAnimationDuration:animationDuration];

float width = self.view.frame.size.width;

float height = self.view.frame.size.height;

CGRect rect = CGRectMake(0.0f, offset , width, height);

self.view.frame = rect;

[UIView commitAnimations];

}

//完成编辑的时候下移回来（只要把offset重新设为0就行了）




- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    [UIView animateWithDuration:0.2 animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, -100);
    }];
    
    return YES;
}


- (void)textViewDidEndEditing:(UITextView *)textView{

    [UIView animateWithDuration:0.2 animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];


}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
